package com.atguigu.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

import com.atguigu.bean.Viewbean;
import com.atguigu.client.SkuViewFeignClient;


import com.atguigu.entity.SkuView;


import com.atguigu.entity.SkuViewExcel;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.stream.Collectors;


/**
 * export
 *
 * @author yangchao
 * @version 开发阶段
 * @description TODO
 * @date 2022/3/9 10:00
 */
@RestController
@RequestMapping("/excel")
public class ExportController {
    @Resource
    private SkuViewFeignClient skuViewFeignClient;

    @GetMapping("/exportExcel")
    public void exportCreditLoadListExcel(
             Viewbean viewbean,
            HttpServletResponse response) throws Exception {
        List<SkuView> list= skuViewFeignClient.exportexcel(viewbean);
        List<SkuViewExcel> collect = list.stream().map(e -> {
            SkuViewExcel skuViewExcel = new SkuViewExcel();
            BeanUtils.copyProperties(e, skuViewExcel);
            return skuViewExcel;
        }).collect(Collectors.toList());

        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        String fileName = "电商网站";
        com.alibaba.excel.metadata.Sheet sheet = new Sheet(1, 0, SkuViewExcel.class);
        //设置自适应宽度
        sheet.setAutoWidth(Boolean.TRUE);

        // 第一个 sheet 名称
        sheet.setSheetName("商品访问量");
        writer.write(collect, sheet);
        //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
        writer.finish();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        out.flush();
    }


}
